<template>
  <div v-loading="loading" class="state">
    <el-form
      ref="form"
      :class="isCard ? 'meeting-card' : ''"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="dataForm vote meeting-card"
      style="width: 100%;"
    >
      <div class="info">
        <el-row>
          <!--          <el-col :span="24">-->
          <!--            <div v-if="showProcessBtn" style="text-align: right;margin-top: 10px">-->
          <!--              <el-button v-if="!showProcessBtn" @click="cancel()">{{ $t("取消") }}</el-button>-->
          <!--              <el-button v-if="form.actStatus !== 'D' && form.actStatus !== 'W'" type="primary" @click="submitForm('save')">{{ $t("保存") }}</el-button>-->
          <!--              <el-button v-if="form.actStatus !== 'D' && form.actStatus !== 'W'" type="primary" @click="submitForm('process')">{{ $t(voteStatus === 'W' ? '重新发起投票' : "保存并发起投票") }}</el-button>-->
          <!--              <el-button v-if="form.actStatus === 'D'" type="primary" @click="stopProcess">{{ $t("终止投票") }}</el-button>-->
          <!--            </div>-->
          <!--          </el-col>-->
          <el-col :span="24">
            <div class="area-header" style="margin-top: 15px;display: flex;align-items: center" @click="expandHandler">
              <span class="area-header-title" style="flex: 0 auto">{{ $t('申请信息') }}</span>
              <span style="color: #409EFF;cursor: pointer" @click.stop="expandHandler">{{ infoShow ? $t('点击收起') : $t('点击展开') }}</span>
              <div v-if="showProcessBtn" style="text-align: right;margin-top: 10px;flex: 1">
                <el-button v-if="!showProcessBtn" size="mini" @click="cancel()">{{ $t("取消") }}</el-button>
                <el-button v-if="form.actStatus !== 'D' && form.actStatus !== 'W'" size="mini" type="primary" @click="submitForm('save')">{{ $t("保存") }}</el-button>
                <el-button v-if="form.actStatus !== 'D' && form.actStatus !== 'W'" size="mini" type="primary" @click="submitForm('process')">{{ $t(voteStatus === 'W' ? '重新发起投票' : "保存并发起投票") }}</el-button>
                <el-button v-if="form.actStatus === 'D'" size="mini" type="primary" @click="stopProcess">{{ $t("终止投票") }}</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
        <div v-if="infoShow">
          <el-row style="flex-wrap: wrap;display: flex">
            <el-col :span="12">
              <el-form-item :label="$t('项目名称')" prop="dealId">
                <template>
                  <router-link
                    target="_blank"
                    :to="{path:'/deal/home/dealBaseHome',query:{id:form.dealId,companyId:form.companyId}}"
                    class="link_a"
                  >{{ form.dealName }}
                  </router-link>
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('标的公司')" prop="companyId">
                <template>
                  <router-link
                    target="_blank"
                    :to="{path:'/company/base/companyBaseHome',query:{companyId:form.companyId}}"
                    class="link_a"
                  >{{ form.companyName }}
                  </router-link>
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('项目负责人')" prop="personCharge">
                <UserSelect v-model="form.personCharge" disabled :placeholder="$t('项目负责人')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('投资主体')" prop="investId">
                <fund-select
                  v-model="form.investId"
                  :is-short="true"
                  :placeholder="$t('投资主体')"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col v-if="!form.icMeetingId" :span="12">
              <el-form-item :label="$t('预计投资金额') + $t('金额单位')" prop="expectedInvestAmount">
                <Money v-model="form.expectedInvestAmount" disabled :placeholder="$t('预计投资金额')" unit="w" />
              </el-form-item>
            </el-col>
            <el-col v-if="!form.icMeetingId" :span="12">
              <el-form-item :label="$t('投资币种')" prop="investCurrency">
                <dict-select v-model="form.investCurrency" disabled :placeholder="$t('投资币种')" dictionary="currency" />
              </el-form-item>
            </el-col>
            <el-col v-if="form.itemType" :span="12">
              <el-form-item :label="$t('事项类型')" prop="itemType">
                <dict-select v-model="form.itemType" disabled :placeholder="$t('事项类型')" dictionary="ic_item_type" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t('投票人员')" prop="voteUser">
                <user-select v-model="form.voteUser" multiple :placeholder="$t('投票人员')" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t('申请标题')" prop="actTitle">
                <el-input v-model="form.actTitle" maxlength="200" show-word-limit :placeholder="$t('申请标题')" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t('申请内容')" prop="applyContent">
                <EditorTxt v-if="!loading" ref="editorTxt" v-model="form.applyContent" :disabled="editorDisabled" :height="400" :placeholder="$t('申请内容')" />
              </el-form-item>
            </el-col>
          </el-row>
          <FileTable
            :business-id="form.dealId"
            :list.sync="form.fileList"
            data-type="mt_vote_main"
            :btn-show="!otherBtnHide"
          />
        </div>
        <el-row v-if="voteStatus === 'W'">
          <el-col :span="24">
            <div class="area-header" style="margin-top: 15px">
              <span class="area-header-title" style="flex: 0 auto">{{ $t('投票结果') }}</span>
            </div>
          </el-col>
          <el-col :span="24">
            <el-table v-loading="loading" class="voteTable" :data="form.voteCountList" border>
              <el-table-column :show-overflow-tooltip="false" :label="$t('投票结果')" align="center" prop="voteStatusLabel" />
              <el-table-column :show-overflow-tooltip="false" :label="$t('票数')" align="center" prop="count" />
            </el-table>
          </el-col>
        </el-row>
        <el-row v-if="voteStatus === 'W' && form.showDetail">
          <el-col :span="24">
            <div class="area-header" style="margin-top: 15px">
              <span class="area-header-title" style="flex: 0 auto">{{ $t('投票明细') }}</span>
            </div>
          </el-col>
          <el-col :span="24">
            <el-table v-loading="loading" tooltip-effect="darkTable" :data="form.detailList" border>
              <el-table-column :label="$t('用户名称')" align="center" prop="userName" />
              <el-table-column :label="$t('投票结果')" align="center" prop="voteStatusLabel" />
              <el-table-column :label="$t('投票时间')" align="center" prop="voteDate">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.voteDate,'{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column :label="$t('意见')" align="center" prop="voteComment" />
              <!--              <el-table-column :label="$t('操作')" align="center" prop="userId">-->
              <!--                <template slot-scope="scope">-->
              <!--                  <el-button type="text" @click="sendMessage(scope.row)">{{ $t('发送提醒') }}</el-button>-->
              <!--                </template>-->
              <!--              </el-table-column>-->
            </el-table>
          </el-col>
        </el-row>
      </div>
      <div v-if="form.actId && showProcess">
        <div class="actTaskLeft actTaskForm" style="padding-left: 0;border: none !important;">
          <!--流转记录-->
          <div>
            <approval-record :act-id="form.actId" />
          </div>
        </div>
        <div class="actTaskLeft" style="border-right: 0px">
          <!--流程图-->
          <act-flow-chart v-if="showProcess" :act-id="form.actId" />
        </div>
      </div>
    </el-form>
    <div v-if="showBtn" slot="footer" class="dialog-footer" style="text-align: right;margin-top: 10px">
      <el-button @click="cancel()">{{ $t("取消") }}</el-button>
      <el-button v-if="form.actStatus !== 'D' && form.actStatus !== 'W'" type="primary" @click="submitForm('save')">{{ $t("保存") }}</el-button>
      <el-button v-if="form.actStatus !== 'D' && form.actStatus !== 'W'" type="primary" @click="submitForm('process')">{{ $t(voteStatus === 'W' ? '重新发起投票' : "保存并发起投票") }}</el-button>
      <el-button v-if="form.actStatus === 'D'" type="primary" @click="stopProcess">{{ $t("终止投票") }}</el-button>
    </div>
  </div>
</template>

<script>
import FundSelect from '@/components/Select/fundSelect.vue'
import EditorTxt from '@/components/Tinymce'
import { getFundName } from '@/api/fund/fundBase'
import ApprovalRecord from '@/components/Act/ApprovalRecord/index.vue'
import ActFlowChart from '@/views/act/process/actFlowChart.vue'
import { getMtVoteMain, saveMtVoteMain, sendVoteMessage } from '@/api/meeting/vote/mtVoteMain'
import { getDealName } from '@/api/base/deal/dealBase'
import { stop } from '@/api/act/process/actProcess'

export default {
  components: { ActFlowChart, ApprovalRecord, EditorTxt, FundSelect },
  props: {
    source: {
      type: String,
      default: undefined
    }
  },
  data() {
    return {
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        investId: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        personCharge: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        expectedInvestAmount: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        investCurrency: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        actTitle: [{ required: true, message: this.$t('必填信息'), trigger: ['blur'] }],
        applyContent: [
          { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] },
          { validator: this.validateContent, trigger: ['blur', 'change'] }
        ],
        voteUser: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        agencyId: [{ required: true, message: this.$t('必填信息'), trigger: ['blur'] }],
        agencyTeam: [{ required: true, message: this.$t('必填信息'), trigger: ['blur'] }],
        agencyAmount: [{ required: true, message: this.$t('必填信息'), trigger: ['blur'] }],
        bidFlag: [{ required: true, message: this.$t('必填信息'), trigger: ['blur'] }]

      },
      btnHide: false,
      voteStatus: undefined,
      // 遮罩层
      loading: false,
      // 操作按钮默认不展示
      buttonShow: true,
      otherBtnHide: false,
      isCard: false,
      fundList: [],
      isInit: false,
      sourceTitle: undefined,
      financeList: [],
      legalList: [],
      industryList: [],
      showBtn: true,
      backdropList: [],
      otherList: [],
      teamList: {},
      type: undefined,
      sourceActTitle: '',
      editorDisabled: false,
      formActTitle: '',
      infoShow: true,
      showProcess: true,
      initData: null,
      itemTypeOptions: [],
      openType: undefined,
      showProcessBtn: false
    }
  },
  created() {
    this.getDicts('ic_item_type').then(res => {
      this.itemTypeOptions = res.data
    })
    if ((this.$route.query.id || this.source === 'sheet') && this.openType !== 'ic') {
      this.$bus.$emit('async_meeting_done')
    } else {
      this.$bus.$emit('async_done')
    }
  },
  methods: {
    // 初始化数据
    init(data) {
      this.initData = data
      this.showProcess = false
      this.otherBtnHide = data.otherBtnHide
      this.showBtn = data.showBtn
      this.showProcessBtn = this.$route.query.id && data.type !== 'ic'
      this.showProcess = !data.actProcessDefKey
      this.loading = true

      // IC会投票
      this.openType = data.type

      if (data != null && data.id || data.meetingId) {
        var id = data.id || data.meetingId
        getMtVoteMain(id).then(async res => {
          this.form = res.data
          this.voteStatus = this.form.actStatus
          if (data.process) {
            // this.form.actId = undefined
            this.form.actStatus = 'N'
          }
          var actId = this.form.actId
          this.form.actId = undefined
          if (!this.form.id) {
            this.form.actTitle = await this.getActTitle(res.data)
          }
          if (this.form.voteProcess) {
            if (this.$parent?.$parent?.$parent?.$parent?.$parent?.$parent?.hideProcess) {
              this.$parent.$parent.$parent.$parent.$parent.$parent.hideProcess(false)
            }
          }
          this.infoShow = this.form.actStatus !== 'W'
          setTimeout(() => {
            this.form.actId = actId
            this.loading = false
          }, 300)
        })
      } else {
        this.reset()
        this.loading = false
      }
    },
    validateContent(rule, value, cb) {
      var num = this.form.applyContent.length
      try {
        // const text = this.$refs.editorTxt.$el.innerText
        // var temp = text.split('\n')
        // temp = temp[temp.length - 1]
        // num = Number(temp.replace('字', ''))
        num = this.$refs.editorTxt.wordcount

        if (isNaN(Number(num))) {
          num = this.form.applyContent.length
        }
      } catch (e) {
        console.error(e)
        num = this.form.applyContent.length
      }

      if (num > 2000) {
        cb(new Error(this.$t('字数不能超过2000')))
      } else {
        cb()
      }
    },
    async getActTitle(data) {
      var dealId = data.dealId
      var fundId = data.investId
      var dealName = await getDealName(dealId)
      var fundName = await getFundName(fundId)
      var actTitle = (fundName ? fundName + '-' : '') + (dealName ? dealName + '-' : '') + (data.itemType ? this.selectDictLabel(this.itemTypeOptions, data.itemType) + '-' : '') + '发起投票'
      return actTitle
    },
    sendMessage(row) {
      sendVoteMessage(row.id).then(() => {
        this.$message.success(this.$t('操作成功'))
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        dealId: undefined,
        emailId: undefined,
        companyId: undefined,
        meetingType: undefined,
        personCharge: undefined,
        investId: undefined,
        expectedInvestAmount: undefined,
        investCurrency: 'CNY',
        actTitle: undefined,
        applyContent: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        financeList: [],
        legalList: [],
        backdropList: [],
        industryList: [],
        otherList: [],
        itemType: undefined
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.voteFormOpen = false
      this.$parent.$parent.reset()
    },
    expandHandler() {
      this.infoShow = !this.infoShow
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      this.showProcess = false
      // 关闭form页面
      if (this.$parent.$parent.voteFormOpen !== undefined) {
        this.$parent.$parent.voteFormOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm(type) {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(valid => {
          // 验证数据
          if (valid) {
            // 弹出遮罩层
            this.loading = true
            // 保存数据
            saveMtVoteMain(this.form).then(response => {
              if (response.code === 200) {
                if (type === 'save') {
                  this.msgSuccess(this.$t('保存成功'))
                  this.showProcess = false
                  if (!this.$route.query.id || this.openType === 'ic') {
                    this.closeForm()
                  }
                } else {
                  this.startProcess(response.data.id)
                  resolve(response.data.id)
                }
                this.loading = false
              } else {
                this.msgError(response.msg)
                this.loading = false
                reject()
              }
            })
          } else {
            this.locationError(document)
          }
        })
      }).catch(() => {
        this.loading = false
      })
    },
    // 启动流程
    startProcess(dataId) {
      this.loading = false
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = this.$t(this.form.actTitle)
      // 业务表名
      processData.dataTable = this.$t('mt_vote_main')
      // 业务ID
      processData.dataId = dataId
      // 业务表单地址(待办页面需要打开的页面)
      processData.formPath = '@/views/deal/mt/vote/mtVoteForm.vue'
      // // 菜单标识(根据菜单标识判断的走哪个流程)
      // processData.menuKey = this.$t('菜单标识')
      processData.processKey = this.form.voteProcess
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        if (!this.$route.query.id || this.openType === 'ic') {
          this.closeForm()
        } else {
          this.init(this.initData)
        }
      })
    },
    // 终止流程
    stopProcess() {
      this.$prompt('', this.$t('终止原因'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        inputErrorMessage: this.$t('终止原因不能为空'),
        inputValidator: (reason) => {
          if (reason === null || reason === '' || reason.trim().length < 1) {
            return this.$t('终止原因不能为空')
          }
        }
      }).then(({ value }) => {
        this.loading = true
        stop(this.form.actId, value).then(response => {
          if (response.code === 200) {
            this.form.actStatus = 'Z'
            this.msgSuccess(this.$t('终止成功'))
            this.showProcess = false
            var actId = this.form.actId
            this.form.actId = undefined
            if (!this.$route.query.id || this.openType === 'ic') {
              this.reset()
              this.closeForm()
            } else {
              setTimeout(() => {
                this.showProcess = true
                this.form.actId = actId
              }, 300)
            }
            this.loading = false
          }
        }).catch(() => {
          this.loading = false
        })
      }).catch(() => {
      })
    }

  }

}
</script>
<style scoped lang="scss">
/deep/ .dataForm .avatar-uploader {
  display: none;
}

.area-header {
  margin-top: 10px;
}

/deep/ .dataForm .el-row .el-form-item {
  min-height: unset;
}

/deep/ .dataForm .el-row .el-form-item.is-error {
  min-height: 54px;
}
/deep/.arrow-icon{
  transition: all linear .2s 0s;
}
/deep/.arrow-icon.rotate{
  transform: rotate(-90deg);
}
/deep/.dataForm.vote::-webkit-scrollbar{
  width: 1px !important;
}
/deep/.voteTable td {
  padding: 0;
}
/deep/.voteTable.el-table .cell{
  text-overflow: unset!important;
}
</style>
